package com.example.demo.msg.aio.client;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.util.concurrent.CountDownLatch;

public class WriteHandle  implements CompletionHandler<Integer,ByteBuffer> {

    private AsynchronousSocketChannel channel;

    private CountDownLatch latch;


    public WriteHandle(AsynchronousSocketChannel channel,CountDownLatch latch) {
        this.channel = channel;
        this.latch = latch;
    }

    @Override
    public void completed(Integer integer, ByteBuffer byteBuffer) {
        if(byteBuffer.hasRemaining()){
            channel.write(byteBuffer,byteBuffer,this);
        }else{

            //创建新的Buffer
            ByteBuffer readBuffer = ByteBuffer.allocate(1024);
            //异步读  第三个参数为接收消息回调的业务Handler
            channel.read(readBuffer, readBuffer, new ReadHandle(channel,latch));
        }

    }

    @Override
    public void failed(Throwable throwable, ByteBuffer byteBuffer) {
        System.err.println("数据发送失败...");
        try {
            channel.close();
            latch.countDown();
        } catch (IOException e) {

            e.printStackTrace();
        }

    }
}